import { defineStore } from 'pinia'
import { getLocalSetting, setLocalSetting } from './helper'
import storage from '@/utils/storage/index.js'
import { store } from '@/store'
import { getSiteCodeBySitDomain } from '@/config/project';
import { ref } from 'vue'


export const useAppStore = defineStore('app-store', () => {
  // state
  const siteInfo = ref({})
  const siderCollapsed = ref(false)
  const theme = ref(undefined)
  const language = ref(undefined)
  // 首页
  const homeCategory = ref(uni.getStorageSync('homeCategory') || [])

  // actions

  // 存储首页菜单
  function setHomeCategoryList(data) {
    homeCategory.value = data
    uni.setStorageSync('homeCategory', data)
  }

  // 筛选首页菜单
  function filterHomeCategory(modelTypeId) {
    return homeCategory.value.find(item => item.modelTypeId === modelTypeId).id
  }




  function setSiderCollapsed(collapsed) {
    siderCollapsed.value = collapsed
    recordState()
  }

  function setSiteInfo(info) {
    info.siteCode = getSiteCodeBySitDomain(info.siteDomain)
    siteInfo.value = info
    storage.set('siteInfo', info)
    storage.set('siteCode', info.siteCode)
    if (localStorage) {
      localStorage.setItem('projectCode', info.code)
      localStorage.setItem('projectName', info.name)
    }
  }

  function setTheme(t) {
    theme.value = t
    recordState()
  }

  function setLanguage(l) {
    if (language.value !== l) {
      language.value = l
      recordState()
    }
  }

  function recordState() {
    setLocalSetting({
      siteInfo: siteInfo.value,
      siderCollapsed: siderCollapsed.value,
      theme: theme.value,
      language: language.value,
    })
  }

  return {
    siteInfo,
    siderCollapsed,
    theme,
    language,
    setSiderCollapsed,
    setSiteInfo,
    setTheme,
    setLanguage,
    recordState,
    homeCategory,
    setHomeCategoryList,
    filterHomeCategory
  }
})

export function useAppStoreWithOut() {
  return useAppStore(store)
}
